<template>
  <div class="profile-container">
    <div class="page-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧个人信息 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button 
                type="primary" 
                :loading="loading"
                @click="handleSave"
              >
                保存修改
              </el-button>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="用户名">
              <el-input v-model="form.username" disabled />
              <div class="form-tip">用户名不可修改</div>
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="form.nickname"
                placeholder="请输入昵称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱地址"
                type="email"
              />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>

            <el-form-item label="头像" prop="avatar">
              <div class="avatar-upload">
                <AvatarUpload
                  v-model="form.avatar"
                  size="large"
                  fit="cover"
                  @success="handleAvatarSuccess"
                />  
                <div class="avatar-tips">
                  <p>点击上传头像</p>
                  <p class="tip-text">支持 JPG、PNG 格式，文件大小不超过 1MB</p>
                </div>
              </div>
            </el-form-item>


          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧操作区 -->
      <el-col :span="8">
        <!-- 账户安全 -->
        <el-card class="security-card">
          <template #header>
            <span>账户安全</span>
          </template>

          <div class="security-item">
            <div class="security-info">
              <div class="security-title">登录密码</div>
              <div class="security-desc">定期更换密码可以提高账户安全性</div>
            </div>
            <el-button type="primary" link @click="showChangePassword = true">
              修改密码
            </el-button>
          </div>

          <el-divider />

          <div class="security-item">
            <div class="security-info">
              <div class="security-title">最后登录</div>
              <div class="security-desc">{{ formatLastLogin }}</div>
            </div>
          </div>
        </el-card>

        <!-- 账户统计 -->
        <el-card class="stats-card">
          <template #header>
            <span>账户统计</span>
          </template>

          <div class="stat-item">
            <div class="stat-label">注册时间</div>
            <div class="stat-value">{{ formatCreatedAt }}</div>
          </div>

          <div class="stat-item">
            <div class="stat-label">角色权限</div>
            <div class="stat-value">
              <el-tag
                v-for="role in userStore.userInfo?.roles"
                :key="role.id"
                type="primary"
                size="small"
                style="margin-right: 5px;"
              >
                {{ role.name }}
              </el-tag>
              <span v-if="!userStore.userInfo?.roles?.length" class="text-gray">
                未分配角色
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <ChangePasswordDialog
      v-model:visible="showChangePassword"
      @success="handlePasswordChanged"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserInfo } from './api'
import { useUserStore } from './store'
import ChangePasswordDialog from './components/ChangePasswordDialog.vue'
import AvatarUpload from '@/components/upload/AvatarUpload.vue'

const userStore = useUserStore()

// 响应式数据
const formRef = ref()
const loading = ref(false)
const showChangePassword = ref(false)

// 表单数据
const form = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^$|^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 计算属性
const formatLastLogin = computed(() => {
  const lastLogin = userStore.userInfo?.last_login_at
  if (!lastLogin) return '暂无记录'
  return new Date(lastLogin).toLocaleString('zh-CN')
})

const formatCreatedAt = computed(() => {
  const createdAt = userStore.userInfo?.created_at
  if (!createdAt) return '暂无记录'
  return new Date(createdAt).toLocaleDateString('zh-CN')
})

// 初始化表单数据
const initForm = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    form.username = userInfo.username || ''
    form.nickname = userInfo.nickname || ''
    form.email = userInfo.email || ''
    form.phone = userInfo.phone || ''
    form.avatar = userInfo.avatar || ''
  }
}

// 头像上传成功回调
const handleAvatarSuccess = (fileInfo) => {
  form.avatar = fileInfo.url
  ElMessage.success('头像上传成功')
}

// 保存个人信息
const handleSave = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const updateData = {
      nickname: form.nickname,
      email: form.email,
      phone: form.phone,
      avatar: form.avatar
    }

    await updateUserInfo(updateData)
    
    // 更新store中的用户信息
    await userStore.getUserInfo()
    
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('更新失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 密码修改成功回调
const handlePasswordChanged = () => {
  ElMessage.success('密码修改成功，请重新登录')
  // 可以选择是否强制重新登录
}

// 页面初始化
onMounted(() => {
  initForm()
})
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  max-width: 600px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-tips p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.tip-text {
  font-size: 12px !important;
  color: #909399 !important;
  margin-top: 4px !important;
}

.security-card,
.stats-card {
  margin-bottom: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.security-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.security-desc {
  font-size: 12px;
  color: #909399;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.text-gray {
  color: #909399;
}
</style>
